package com.czk.gulimall.order.web;

import com.czk.common.exception.NoStockException;
import com.czk.gulimall.order.service.OrderService;
import com.czk.gulimall.order.vo.OrderConfirmVo;
import com.czk.gulimall.order.vo.OrderSubmitVo;
import com.czk.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/4/26 19:49
 */
@Controller
@Slf4j
public class OrderWebController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model) {

        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmOrderData", confirmVo);
        return "confirm";
    }

    /**
     * 下单功能
     *
     * @param orderSubmitVo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, RedirectAttributes redirectAttributes) {
        // 下单 创建订单、验证令牌、验价格、锁库存
        // 下单成功去支付页
        // 下单失败回到订单确认页，重新确认信息
        log.info("订单提交的数据{}", orderSubmitVo);
        try {
            SubmitOrderResponseVo submitOrderResponseVo = orderService.submitOrder(orderSubmitVo);
            if (submitOrderResponseVo.getCode() == 0) {
                // 成功
                return "pay";
            } else {
                String msg = "下单失败：";
                switch (submitOrderResponseVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，情重新提交";
                        break;
                    case 2:
                        msg += "商品价格发生变化，请重新提交";
                        break;
                    case 3:
                        msg += "库存不足";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
            }
        }catch (NoStockException ex){
            if (ex instanceof NoStockException){
                String message=((NoStockException) ex).getMessage();
                redirectAttributes.addFlashAttribute("msg",message);
            }
        }
        return "redirect:http://order.gulimall.com/toTrade";
    }
}
